package handler

import (
	"ball/api/request"
	"ball/internal/dao"
	"ball/internal/model"
	"ball/pkg"
	"github.com/gin-gonic/gin"
	"net/http"
)

func Login(c *gin.Context) {
	var req request.LoginReq
	if err := c.ShouldBind(&req); err != nil {
		c.JSON(http.StatusOK, gin.H{
			"code": 10000,
			"msg":  "验证失败",
			"data": err.Error(),
		})
		return
	}
	user := dao.GetUser(req.Tel)
	if user.Id == 0 {
		users := model.Users{
			Tel:      req.Tel,
			Password: req.Password,
		}
		if !dao.Create(&users) {
			c.JSON(http.StatusOK, gin.H{
				"code": 10000,
				"msg":  "创建失败",
				"data": nil,
			})
			return
		}
		c.JSON(http.StatusOK, gin.H{
			"code": 200,
			"msg":  "创建成功",
			"data": users,
		})
		return
	}
	if user.Password != req.Password {
		c.JSON(http.StatusOK, gin.H{
			"code": 10000,
			"msg":  "登录失败",
			"data": nil,
		})
		return
	}
	token, _ := pkg.NewJWT("2210a").CreateToken(pkg.CustomClaims{
		ID: uint(user.Id)})
	c.JSON(http.StatusOK, gin.H{
		"code": 200,
		"msg":  "登录成功",
		"data": token,
	})
	return
}
